package com.cskaoyan.wordmemorize.controller.app;

import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.PayOrderDTO;
import com.cskaoyan.wordmemorize.dto.app.VocPaySaleDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.PaySuccessNotifyCommand;
import com.cskaoyan.wordmemorize.request.VocPaySaleCommand;
import com.cskaoyan.wordmemorize.service.UserPayService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/pay")
public class UserPayController {

    @Resource
    UserPayService userPayService;

    /**
     * 用户用于支付
     *
     * @param command VocPaySaleCommand
     * @return 支付订单信息（含支付交易id）
     */
    @PostMapping("")
    public Result<PayOrderDTO> pay(@RequestBody VocPaySaleCommand command) {
        Long userId = StpKit.USER.getLoginIdAsLong();
        PayOrderDTO payOrderDTO = userPayService.pay(command, userId);
        return Result.ok(payOrderDTO);
    }

    /**
     * 用户用于接收支付成功的异步通知
     *
     * @param command PaySuccessNotifyCommand
     * @return "success"
     */
    @PostMapping("/notice")
    public String payNotice(@RequestBody PaySuccessNotifyCommand command) {
        Long userId = StpKit.USER.getLoginIdAsLong();
        return userPayService.paySuccess(command, userId);
    }

    /**
     * 用户用于获取支付结果
     *
     * @param paySaleId 支付交易id
     * @return status（1-初始化，2-支付成功）
     */
    @GetMapping("/{paySaleId}")
    public Result<Integer> queryTradeStatus(@PathVariable Long paySaleId) {
        Integer status = userPayService.queryTradeStatus(paySaleId);
        return Result.ok(status);
    }

    /**
     * 获取购买历史记录
     * GET /user/pay/list
     */
    @GetMapping("/list")
    public Result<PageDTO<VocPaySaleDTO>> getPaySaleHistory(PageRequest pageRequest) {
        Long userId = StpKit.USER.getLoginIdAsLong();
        PageDTO<VocPaySaleDTO> page = userPayService.getPaySaleHistory(userId, pageRequest);
        return Result.ok(page);
    }
}
